package io.gitee.yth.design.pattern.test.core.pattern.behavioral.iterator.code;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;

/**
 * @author yth
 * @since 2023-04-26-21:21
 */
public class College extends Organization {

    private final List<Department> components = new ArrayList<>();

    public College(String name) {
        this.name = name;
    }

    @Override
    public void printAll() {
        System.out.println("college: " + name);
        forEach(e -> System.out.println(e.getName()));
    }

    @Override
    public void add(Organization organization) {
        if (!(organization instanceof Department)) {
            throw new IllegalArgumentException();
        }
        modCount++;
        components.add((Department) organization);
    }

    @Override
    public void remove(Organization organization) {
        if (!(organization instanceof Department)) {
            throw new IllegalArgumentException();
        }
        modCount++;
        components.remove(organization);
    }

    @Override
    public Department getChild(int i) {
        return components.get(i);
    }

    @Override
    public Iterator<Organization> iterator() {
        return new CollegeItr();
    }

    private class CollegeItr implements OrgIterator {

        private int cursor;
        private int expectedModCount = modCount;

        @Override
        public boolean hasNext() {
            return cursor != components.size();
        }

        @Override
        public Organization next() {
            checkForComodification();
            return components.get(cursor++);
        }

        @Override
        public void remove() {
            checkForComodification();
            if (cursor == 0) {
                throw new IllegalStateException();
            }
            components.remove(--cursor);
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
}
